<template>
  <div>
    <div class="login-container clearfix">
      <div class="title">
        <!-- <div class="login-header">
          <img src="../assets/images/logo.png" alt="" />
        </div> -->
      </div>
      <div class="login-box">
        <el-form
          :model="loginForm"
          :rules="loginrules"
          ref="loginForm"
          label-width="100px"
          style="width: 320px; margin-top: 40px"
        >
          <el-form-item label="账号:" prop="account">
            <el-input
              autofocus
              v-model.number="loginForm.account"
              @focus="login_error"
              placeholder="手机号\账号"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码:" prop="password">
            <el-input
              type="password"
              v-model="loginForm.password"
              show-password
              @focus="login_error"
            ></el-input>
          </el-form-item>
          <el-form-item label="验证码" prop="verifycode">
            <div style="display: flex">
              <el-input
                v-model="loginForm.verifycode"
                @keyup.enter.native="login()"
                @focus="login_error"
              ></el-input>
              <span
                @click="refreshCode"
                style="margin-left: 2px; margin-top: 2px"
              >
                <s-identify :identifyCode="identifyCode"></s-identify>
              </span>
            </div>
          </el-form-item>
          <span class="none" id="loginerr">用户名或者密码不正确</span>
          <el-form-item>
            <a href=""></a>
            <el-button type="commit" ref="btn" @click="login()">登录</el-button>
            <el-button @click="register">注册</el-button>
          </el-form-item>
        </el-form>
        <router-link to="/forget"> 忘记密码 </router-link>
      </div>
    </div>
  </div>
</template>

<script>
import SIdentify from "../components/identify.vue";
import { encrypt } from "../plugins/rsaEncrypt"; //引入rsaEncrypt.js
import { mapMutations } from "vuex";
export default {
  components: {
    SIdentify,
  },
  data() {
    var checkaccount = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("账号不能为空"));
      } else {
        callback();
      }
    };
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        callback();
      }
    };
    // 验证码自定义验证规则
    const validateVerifycode = (rule, value, callback) => {
      const newVal = value.toLowerCase();
      const identifyStr = this.identifyCode.toLowerCase();
      if (newVal === "" || newVal === null || newVal === undefined) {
        callback(new Error("请输入验证码"));
      } else if (newVal !== identifyStr) {
        callback(new Error("验证码不正确!"));
      } else {
        callback();
      }
    };
    return {
      identifyCodes: "3456789ABCDEFGHGKMNPQRSTUVWXY",
      identifyCode: " ",
      loginForm: {
        password: "",
        account: "",
        verifycode: "",
      },
      loginrules: {
        password: [{ validator: validatePass, trigger: "blur" }],
        account: [{ validator: checkaccount, trigger: "blur" }],
        verifycode: [{ trigger: "blur", validator: validateVerifycode }],
      },
      dialogVisible: false,
    };
  },
  methods: {
    ...mapMutations(["setToken"]),
    login() {
      this.$refs.loginForm.validate(async (valid) => {
        if (!valid) {
          this.refreshCode();
          this.loginForm.verifycode = "";
          return false;
        } else {
          this.axios
            .post("/user/login", {
              account: this.loginForm.account,
              password: encrypt(this.loginForm.password),
            })
            .then((res) => {
              // console.log(res.data.data.userInfo);
              if (res.data.data.code == 200) {
                this.setToken({
                  token: res.data.data.token,
                  userInfo: res.data.data.userInfo,
                });
                this.$router.push("/home");
              } else {
                console.log(res.data.data);
                document.getElementById("loginerr").className =
                  "login-error-text";
                this.refreshCode();
              }
              // console.log(res.data.data);
            })
            .catch((err) => {
              this.refreshCode();
              console.log(err);
            });
          // document.getElementById("loginerr").className = "login-error-text";
        }
      });
    },
    register() {
      this.$router.push("/register");
    },
    login_error() {
      document.getElementById("loginerr").className = "none";
    },
    // 生成随机数
    randomNum(min, max) {
      return Math.floor(Math.random() * (max - min) + min);
    },
    // 切换验证码
    refreshCode() {
      this.identifyCode = "";
      this.makeCode(this.identifyCodes, 4);
    },
    // 随机生成验证码字符串
    makeCode(data, len) {
      for (let i = 0; i < len; i++) {
        this.identifyCode += data[this.randomNum(0, data.length - 1)];
      }
    },
  },
  mounted() {
    // 验证码初始化
    this.identifyCode = "";
    this.makeCode(this.identifyCodes, 4);
  },
};
</script>

<style scoped>
@import url("../assets/css/base.css");

.login-container {
  width: 100%;
  height: 100%;
  background-size: 100% 100%;
  /* background: url("../assets/images/login5.jpg") no-repeat; */
  background-image: url("../assets/images/wallpaper.jpg");
  position: fixed;
}
.login-box {
  width: 700px;
  height: 700px;
  background-color: #f5f5f5;
}

.login-header {
  width: 400px;
  height: 200px;
  margin-top: 40px;
  margin-left: 20px;
  position: absolute;
}
.login-header img {
  width: 100%;
  height: 100%;
}
.login-box {
  width: 360px;
  height: 360px;
  border-radius: 40px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);

  text-align: center;
}
.login-form {
  width: 320px;
  height: 100%;
  margin: 0 auto;
}
.login-error-text {
  display: block;
  font-size: 12px;
  color: red;
  margin-top: -15px;
  margin-bottom: 15px;
}
.none {
  display: none;
}
.login-box a {
  color: #1ba35266;
  position: absolute;
  left: 47px;
  bottom: 90px;
}
.login-box a:hover {
  color: black;
}
</style>